package org.wu.framework.lazy.orm.database.lambda.stream.script;

import org.wu.framework.core.io.ScriptResource;
import org.wu.framework.core.NormalUsedString;
import org.wu.framework.core.exception.AssertFactory;

import javax.script.ScriptException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class ScriptResourceDatabasePopulator implements DatabasePopulator {
    List<ScriptResource> scriptResources = new ArrayList<>();

    private String sqlScriptEncoding;

    // 脚本分隔符 ;
    private String separator = NormalUsedString.SEMICOLON;

    // 注释  ---
    private String[] commentPrefixes = {NormalUsedString.DUBLE_DASH};
    /**
     * 注释 /*
     */

    private String blockCommentStartDelimiter = NormalUsedString.START_DELIMITER;
    /**
     * 注释 *\/
     */

    private String blockCommentEndDelimiter = NormalUsedString.END_DELIMITER;

    private boolean continueOnError = false;

    private boolean ignoreFailedDrops = false;

    public void setSqlScriptEncoding(String sqlScriptEncoding) {
        this.sqlScriptEncoding = sqlScriptEncoding;
    }

    public void setSeparator(String separator) {
        this.separator = separator;
    }

    public void setCommentPrefixes(String[] commentPrefixes) {
        this.commentPrefixes = commentPrefixes;
    }

    public void setBlockCommentStartDelimiter(String blockCommentStartDelimiter) {
        this.blockCommentStartDelimiter = blockCommentStartDelimiter;
    }

    public void setBlockCommentEndDelimiter(String blockCommentEndDelimiter) {
        this.blockCommentEndDelimiter = blockCommentEndDelimiter;
    }

    public void setContinueOnError(boolean continueOnError) {
        this.continueOnError = continueOnError;
    }

    public void setIgnoreFailedDrops(boolean ignoreFailedDrops) {
        this.ignoreFailedDrops = ignoreFailedDrops;
    }

    public void addScripts(ScriptResource resource) {
        scriptResources.add(resource);
    }

    @Override
    public void populate(Connection connection) throws ScriptException {
        AssertFactory.notNull(connection, "'connection' must not be null");
        for (ScriptResource script : this.scriptResources) {
            ScriptUtils.executeSqlScript(connection, script, this.ignoreFailedDrops,
                    this.commentPrefixes, this.separator, this.blockCommentStartDelimiter, this.blockCommentEndDelimiter);
        }
    }

}
